//引入模块
const  koa=require('koa');
const  Router=  require('koa-router');
const  mongoose =   require('mongoose');
var bodyParser = require('koa-bodyparser');
var bcrypt = require('bcryptjs'); 
const passport = require('koa-passport')
const  path= require("path");
//引进文件
const  db= require('./config/key').mongoURI;
//引进路由模块
const  user = require('./routes/api/user');
const  profile = require('./routes/api/profile');
const  posts = require('./routes/api/posts');
//实例化
const  app=new koa();
const router= new Router();
//使用路由
router.get('/',async  ctx=>{
     ctx.body='hello  world';
})

//连接数据库
mongoose.connect(
     db,
     {useNewUrlParser:true}
).then(()=>{
     console.log('数据库连接成功');
}).catch((err)=>{
      throw(err);
})
//token 
app.use(passport.initialize())
app.use(passport.session())
//回调到config中
require('./config/passport')(passport);
//配置路由地址
router.use('/api/user',user);
router.use('/api/profile',profile);
router.use('/api/posts',posts);
//使用body-parse
app.use(bodyParser());
//配置路由模块
app.use(router.routes()).use(router.allowedMethods());
//访问打包的文件
if(process.env.NODE_ENV==="production")  {
     app.use(express.static("client/build"));
     app.get("*",(req,res)=>{
           res.sendFile(path.resolve(__dirname,"client","build","index.html"));
     })
}


//配置端口
const  port = process.env.PORT||4000;
app.listen(port,()=>{
     console.log('服务器启动在4000');
})
